using System;
using System.Collections.Generic;
using System.IO;
using System.Text.Json;

namespace CleanUpTool.Models
{
    public class DirectoryConfig
    {
        public string Name { get; set; }
        public string Path { get; set; }
        public bool IsEnabled { get; set; } = true;
        public DateTime LastCleanupTime { get; set; }
    }

    public class CleanupConfiguration
    {
        private static readonly string ConfigFilePath = Path.Combine(
            Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData),
            "CleanUpTool",
            "config.json"
        );

        public List<DirectoryConfig> SavedDirectories { get; set; } = new List<DirectoryConfig>();
        public bool AutoScanAfterSelect { get; set; } = true;
        public bool ShowConfirmationBeforeCleanup { get; set; } = true;

        public static CleanupConfiguration Load()
        {
            try
            {
                if (!File.Exists(ConfigFilePath))
                {
                    return new CleanupConfiguration();
                }

                string jsonContent = File.ReadAllText(ConfigFilePath);
                return JsonSerializer.Deserialize<CleanupConfiguration>(jsonContent) ?? new CleanupConfiguration();
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine($"加载配置文件时出错: {ex.Message}");
                return new CleanupConfiguration();
            }
        }

        public void Save()
        {
            try
            {
                string directoryPath = Path.GetDirectoryName(ConfigFilePath);
                if (!Directory.Exists(directoryPath))
                {
                    Directory.CreateDirectory(directoryPath);
                }

                string jsonContent = JsonSerializer.Serialize(this, new JsonSerializerOptions
                {
                    WriteIndented = true
                });

                File.WriteAllText(ConfigFilePath, jsonContent);
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine($"保存配置文件时出错: {ex.Message}");
            }
        }

        public void AddDirectory(string name, string path)
        {
            if (!SavedDirectories.Any(d => d.Path.Equals(path, StringComparison.OrdinalIgnoreCase)))
            {
                SavedDirectories.Add(new DirectoryConfig
                {
                    Name = name,
                    Path = path,
                    LastCleanupTime = DateTime.Now
                });
                Save();
            }
        }

        public void RemoveDirectory(string path)
        {
            SavedDirectories.RemoveAll(d => d.Path.Equals(path, StringComparison.OrdinalIgnoreCase));
            Save();
        }
    }
}